package com.nuanshui.heatedloan.credit.pay.behavior;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.behavior.BehaviorContext;
import com.nuanshui.framework.behavior.IBehaviorInvoker;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.credit.pay.PayContext;
import com.nuanshui.heatedloan.credit.pay.PayRequest;
import com.nuanshui.heatedloan.credit.pay.TransRequestCode;
import com.nuanshui.heatedloan.credit.pay.utils.AllinPayUtil;
import com.nuanshui.heatedloan.credit.pay.validation.PayValidationFacade;
import com.nuanshui.heatedloan.credit.pay.validation.ValidationResult;
import com.nuanshui.heatedloan.credit.pay.validation.ValidationResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public abstract class PayBehavior implements IPayBehaviorInvoker {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Autowired
    private PayValidationFacade payValidationFacade;

    @Override
    public ValidationResult doInvoke() {
        PayRequest request = PayContext.getContext().getPayRequest();
        internalInvoke(request);

        if(PayContext.getContext().hasError())
        {
            AllinPayUtil.logOrderPay(logger, request, "支付发生错误信息: "+ JSON.toJSONString(PayContext.getContext().getValidationResult()));
            return PayContext.getContext().getValidationResult();
        }

        ValidationResult result=validate(request);

        PayContext.getContext().setValidationResult(result);

        if(PayContext.getContext().hasError())
        {
            AllinPayUtil.logOrderPay(logger, request, "支付发生错误信息: "+ JSON.toJSONString(result));
        }

        return result;
    }

    public abstract void internalInvoke(PayRequest request);

    public void internalValidate(ValidationResult result,PayRequest request) {

    }

    public ValidationResult validate(PayRequest request) {

        ValidationResult result = new ValidationResult(ValidationResultCode.VALIDATION_SUCCESS);

        if(TransRequestCode.isPayCode(request.getTransRequestCode()))
        {
            if (SysStringUtils.isNotEmpty((getName()))) {
                ValidationResult executeResult = payValidationFacade.execute(getName(), request);
                if(executeResult!=null)
                {
                    result=executeResult;
                }
            }
            internalValidate(result,request);
        }

        return result;
    }

}
